const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isDev = process.env.NODE_ENV === 'development';
const webpack = require('webpack');
const OptimizeCssAssetsWebpackplugin = require('optimize-css-assets-webpack-plugin');

const config = {
    dev: {
        template: {
            title: 'Webpack 基础 - 开发环境',
            header: false,
        },
    },
    build: {
        template: {
            title: 'Webpack 基础',
            header: false,
        },
    },
};

module.exports = {
    mode: isDev ? 'development' : 'production', // production
    // 入口 src/index.js
    entry: {
        index: './src/index.js',
        // main: './src/main.js',
        // app: './src/App.jsx',
        // test: './src/test.js',
    },
    // 出口 dist/main.js
    // 缓存策略
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].[hash:8].js',
        // publicPath: '/', // CDN 托管我们所有的静态资源，分配到用户访问的各个地区，用于快速加载资源
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        port: 3000, // 默认 8080
        quiet: false, // 默认不启用
        inline: true, // 默认开启 inline 模式，如果设置为 false，开启 iframe 模式
        stats: 'errors-only', // 终端仅打印 error
        overlay: false, // 默认不启用
        clientLogLevel: 'silent', // 日志等级
        compress: true, // 是否启用 gzip 压缩
        progress: true, // 是否显示进度条
        open: true, // 是否自动打开浏览器
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                // include: ['src'],
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env', '@babel/preset-react'],
                    plugins: ['@babel/plugin-transform-runtime'],
                },
            },
            {
                test: /\.vue$/,
                loader: 'vue-loader',
            },
            {
                test: /\.(c|le)ss$/,
                exclude: /node_modules/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: ['postcss-preset-env'],
                            },
                        },
                    },
                    'less-loader',
                ],
            },
            {
                test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/,
                loader: 'url-loader',
                options: {
                    limit: 10240, // 当加载这个资源，少于 10kb 时，会转成 base64 编码（为什么要转，因为要减少请求次数）
                    name: '[name]_[hash:8].[ext]',
                },
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './public/index.html',
            config: config[isDev ? 'dev' : 'build'].template,
        }),
        new CleanWebpackPlugin(),
        new CopyWebpackPlugin({
            patterns: [
                {
                    from: './public/js/*.js',
                    to: path.join(__dirname, 'dist', 'js'),
                    flatten: true,
                    // 过滤函数返回 true 时，才复制
                    filter: async (resourcePath) => {
                        return path.basename(resourcePath) !== 'other.js';
                    },
                },
                {
                    from: './public/css/*.css',
                    to: path.join(__dirname, 'dist', 'css'),
                    flatten: true,
                },
            ],
        }),
        new VueLoaderPlugin(),
        new webpack.ProvidePlugin({
            React: 'react',
        }),
        new MiniCssExtractPlugin({
            filename: '[name]_[hash:10].css',
        }),
        new OptimizeCssAssetsWebpackplugin(),
    ],
};
